package nl.gamayun.whohasit;

import java.util.HashSet;
import java.util.Set;

import nl.gamayun.whohasit.services.WhoHasItService;
import nl.gamayun.whohasit.utils.WhoHasItUtils;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class WhoHasItActivity extends Activity implements OnTouchListener
{

	static final private String	TAG						= WhoHasItActivity.class.getSimpleName();
	static final private int		ABOUT_DIALOG		= 1;
	static final private int		SHOW_PREFERENCES	= 1;
	private static final String 	SELECTED_INDEX_KEY 	= "SELECTED_INDEX_KEY";
	private static final int		REMOVE_LOAN			= Menu.FIRST;
	static public Set<String> 		TEST_DEVICES 		= new HashSet<String>();
	
	private WhoHasItHandler whoHasItHandler;
	private ListView loanListView;
	
	private Intent loanIntent;
	// private Intent listIntent ;
	private Intent service ;
	private AboutDialog aboutDialog;
	private AdView adView;
	


	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	    
		whoHasItHandler = WhoHasItUtils.getWhoHasItHandler(this);
		loanIntent = new Intent(this, LoanActivity.class);
		aboutDialog = new AboutDialog(this, R.style.Dialog);

		if (!((WhoHasIt)getApplication()).isServiceRunning())
		{
			service = new Intent(this, WhoHasItService.class);
			ComponentName name = getApplication().startService(service);
			Log.d(TAG, "Service started:"+name);
		}

		ImageButton buttonAdd = (ImageButton) findViewById(R.id.button_add);
		buttonAdd.setOnClickListener(new OnClickListener()
		{
			public void onClick(View _view)
			{
				loanIntent.putExtra(Loan.LOAN_KEY, 0);
				Log.d(TAG, "bundle:"+loanIntent.getExtras());
				startActivityForResult(loanIntent, LoanActivity.ACITIVITY);
			}
		});
		
		SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.drawer);
		drawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			
			public void onDrawerOpened() {
				ImageView handler = (ImageView) findViewById(R.id.handle);
				handler.setImageResource(R.drawable.slider_handler_down);
			
			}
		});
		drawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			
			public void onDrawerClosed() {
				ImageView handler = (ImageView) findViewById(R.id.handle);
				handler.setImageResource(R.drawable.slider_handler_up);
			}
		});
		
		loanListView = (ListView) findViewById(R.id.loanListView);
		
		loanListView.setAdapter(whoHasItHandler.getLoanAdapter());
		loanListView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> _av, View _v, int _index, long arg3 )
			{
				loanIntent.putExtra(Loan.LOAN_KEY, whoHasItHandler.getLoanAdapter().getItem(_index).getLoanID());
				Log.d(TAG, "bundle:"+loanIntent.getExtras());
				startActivityForResult(loanIntent, LoanActivity.ACITIVITY);
			}
		});
		registerForContextMenu(loanListView);

		// Create the adView
		TEST_DEVICES.add(AdRequest.TEST_EMULATOR);
		TEST_DEVICES.add("emulator-5554");
	    adView = (AdView) findViewById(R.id.main_ad);
	    AdRequest adRequest = new AdRequest();
	    adRequest.setTestDevices(TEST_DEVICES);
	    adView.loadAd(adRequest);
	}

	public boolean onTouch(View v, MotionEvent event)
	{
		Log.d(TAG, "onTouch");
		return false;
	}

	@Override
	protected void onPause()
	{
		Log.d(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		Log.d(TAG, "onResume");
		super.onResume();
		updateSlider();
		updateView();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		Log.d(TAG, "onWindowFocusChanged");
		if (hasFocus)
		{
			updateSlider();
			updateView();
		}
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		Log.d(TAG, "onCreateOptionsMenu");
		super.onCreateOptionsMenu(menu);
		//menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);
		//menu.add(0, MENU_ABOUT, Menu.NONE, R.string.menu_about);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo)
	{
		Log.d(TAG, "onCreateContextMenu");
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.selected_item);
		menu.add(0, REMOVE_LOAN, Menu.NONE, R.string.remove);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Log.d(TAG, "onOptionsItemSelected");
		super.onOptionsItemSelected(item);
		switch (item.getItemId())
		{
			case (R.id.menu_add ):
			{
				addNewItem();
				return true;
			}
			case (R.id.menu_about):
			{
				showDialog(ABOUT_DIALOG);
				return true;
			}
			case (R.id.menu_preferences):
			{
				Intent i = new Intent(this, Preferences.class);
				startActivityForResult(i, SHOW_PREFERENCES);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		Log.d(TAG, "onContextItemSelected");
		super.onContextItemSelected(item);
		switch (item.getItemId())
		{
		case (REMOVE_LOAN):
		{
			AdapterView.AdapterContextMenuInfo menuInfo;
			menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
			int index = menuInfo.position;
			removeItem(index);
			return true;
		}
		}
		return false;
	}

	@Override
	public Dialog onCreateDialog(int id)
	{
		Log.d(TAG, "onCreateDialog");
		switch (id)
		{
		case (ABOUT_DIALOG):
			return aboutDialog;
		}
		return null;
	}

	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		Log.d(TAG, "onSaveInstanceState");
		outState.putInt(SELECTED_INDEX_KEY, loanListView.getSelectedItemPosition());
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState)
	{
		Log.d(TAG, "onRestoreInstanceState");
		int pos = -1;
		if (savedInstanceState != null)
			if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
				pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);
		loanListView.setSelection(pos);
	}

	
	@Override
	public void onDestroy()
	{
		whoHasItHandler.onDestroy();
		adView.destroy();
		super.onDestroy();
	}

	private void updateSlider()
	{
		Log.d(TAG, "updateSlider");

		Integer totalLoansFrom = whoHasItHandler.getNumberOfLoansForType(TYPE.lent_from);
		((TextView) findViewById(R.id.totalLoansFrom)).setText(totalLoansFrom.toString());

		Integer totalLoansTo = whoHasItHandler.getNumberOfLoansForType(TYPE.lent_to); 
		((TextView) findViewById(R.id.totalLoansTo)).setText(totalLoansTo.toString());
		
		Loan newestLoan = whoHasItHandler.getNewestLoan();
		String newestLoanString = newestLoan == null ? getText(R.string.unknown).toString() : newestLoan.getDetailSmall();
		((TextView) findViewById(R.id.newestLoan)).setText(newestLoanString);
		
		Loan oldestLoan = whoHasItHandler.getOldestLoan();
		String oldestLoanString = oldestLoan==null ? getText(R.string.unknown).toString() : oldestLoan.getDetailSmall();
		((TextView) findViewById(R.id.oldestLoan)).setText(oldestLoanString);
		
		String lentMostTo = whoHasItHandler.getLentMostTo();
		((TextView) findViewById(R.id.lentMostTo)).setText(lentMostTo);

		String lentMostFrom = whoHasItHandler.getLentMostFrom();
		((TextView) findViewById(R.id.lentMostFrom)).setText(lentMostFrom);
		
}

	private void updateView()
	{
		Log.d(TAG, "updateView");

		String totalLoans = getString(R.string.totalLoans, whoHasItHandler.getNumberOfLoans());
		((TextView) findViewById(R.id.totalLoans)).setText(totalLoans);
		
}

	private void addNewItem()
	{
		Log.d(TAG, "addNewItem");
		loanIntent.putExtra(Loan.LOAN_KEY, 0);
		startActivityForResult(loanIntent, LoanActivity.ACITIVITY);
	}

	private void removeItem(int _index)
	{
		Log.d(TAG, "removeItem");
		Loan loan = whoHasItHandler.getLoanAdapter().getItem(_index);
		whoHasItHandler.removeLoan(loan);
	}

}
